<?
class GestaoDate extends Type
{
	static protected $language = array ('en_US' => 'en', 'pt_BR' => 'pt', 'es_ES' => 'es');
	
	protected $firstYear = 0;
	
	protected $lastYear = 0;
	
	protected $showTime = FALSE;
	
	protected $value = array (0, 0, 0);
	
	public function __construct ($table, $field)
	{
		parent::__construct ($table, $field);
		
		$this->value = array (0, 0, 0);
		
		if (array_key_exists ('value', $field))
			$this->setValue (explode ('-', $field ['value']));
		
		if (array_key_exists ('first-year', $field))
			if (!is_numeric ($field ['first-year']) && trim ($field ['first-year']) == '[now]')
				$this->setFirstYear (date ('Y'));
			else
				$this->setFirstYear ($field ['first-year']);
			
		if (array_key_exists ('last-year', $field))
			if (!is_numeric ($field ['last-year']) && trim ($field ['last-year']) == '[now]')
				$this->setLastYear (date ('Y'));
			else
				$this->setLastYear ($field ['last-year']);
		
		if (array_key_exists ('show-time', $field))
			$this->setShowTime (strtoupper ($field ['show-time']) == 'TRUE' ? TRUE : FALSE);
	}
	
	public function setValue ($value)
	{
		if (!is_array ($value))
		{
			$value = explode ('-', $value);
			
			array_walk ($value, array ($this, 'toInteger'));
		}
		
		$this->value = $value;
	}
	
	public function setFirstYear ($firstYear)
	{
		$firstYear = trim ($firstYear);
		
		if ($firstYear == '[now]')
			$firstYear = date ('Y');
		
		$this->firstYear = (int) $firstYear;
	}
	
	public function getFirstYear ()
	{
		return $this->firstYear;
	}
	
	public function setLastYear ($lastYear)
	{
		$lastYear = trim ($lastYear);
		
		if ($lastYear == '[now]')
			$lastYear = date ('Y');
		
		$this->lastYear = (int) $lastYear;
	}
	
	public function getLastYear ()
	{
		return $this->lastYear;
	}
	
	public function setShowTime ($showTime)
	{
		$this->showTime = (bool) $showTime;
	}
	
	public function showTime ()
	{
		return (bool) $this->showTime;
	}
	
	public function isEmpty ()
	{
		$value = $this->getValue ();
		
		if (!is_array ($value) || !array_sum ($value))
			return TRUE;
		
		return FALSE;
	}
	
	public function getUnixTime ()
	{
		$aux = $this->getValue ();
		
		return (int) mktime (0, 0, 0, $aux [1], $aux [0], $aux [2]);
	}
	
	public function __toString ()
	{
		$aux = $this->getValue ();
		
		array_walk ($aux, array ($this, 'toString'));
		
		return implode ('-', $aux);
	}
	
	public static function toInteger (&$item, $key)
	{
		$item = (int) $item;
	}
	
	public static function toString (&$item, $key)
	{
		$item = $item < 10 ? '0'. (string) $item : (string) $item;
	}
	
	public static function getLanguage ()
	{
		return array_key_exists (Locale::singleton ()->getLanguage (), self::$language) ? self::$language [Locale::singleton ()->getLanguage ()] : reset (self::$language);
	}
}
?>